<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <CommonDateSearch ref="searchRef" @search="handleSearch"></CommonDateSearch>
    <div class="content-box">
      <div class="chart-box" v-for="item in typeList" :key="item.dictCode">
        <Line class="chart" :loading="item.loading" :chartData="item.chartData" :title="item.itemName"
          :unit="item.chartData.unit" />
      </div>
    </div>
  </PageWrapper>
</template>

<script setup>
import Line from './indexLine.vue'
import { ref, onMounted, reactive } from 'vue'
import { PageWrapper } from '@/components/Page'
import { getChartListData } from '@/api/common/chart'
import { getDictListByCode } from '@/api/sys/dict'
import CommonDateSearch from './CommonDateSearch.vue'
import { getEleThisData, thisDataUnitConsumption } from '@/api/power/electricity/electricity.ts'

defineOptions({ name: 'Lighting' })

// 定义图表类型枚举（用于排序）
const ChartTypeEnum = {
  CLEAN_POWER: '洁净区域照明电耗',    // 洁净区电耗
  CLEAN_UNIT: '洁净区域照明单耗',     // 洁净区单耗
  SUPPORT_POWER: '支持区域照明电耗',  // 支持区电耗
  SUPPORT_UNIT: '支持区域照明单耗'    // 支持区单耗
}

const searchRef = ref()
const searchInfo = reactive({})
const typeList = ref([])
const dictCode = 'lighting_power_consumption'

onMounted(async () => {
  await getTypeList()
  searchRef.value.handleSearch()
})

const handleSearch = (params) => {
  Object.assign(searchInfo, params)
  getChartData()
}

const getTypeList = async () => {
  const res = await getDictListByCode(dictCode)
  typeList.value = res.map((item) => ({
    ...item,
    loading: true,
    chartData: {
      xaxisList: [],
      yaxisList: [],
      unit: 'kWh' // 添加默认单位
    },
  }))
}

const getChartData = async () => {
  // 模拟数据（仅作示例，实际应从接口获取）
  const mockData = [
    {
      xaxisList: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00',
      ],
      yaxisList: [
        {
          name: '洁净区域照明电耗',
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          stack: '1777562657152888832',
        },
      ],
      unit: 'kWh' // 电耗单位改为kWh
    },
    {
      xaxisList: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00',
      ],
      yaxisList: [
        {
          name: '支持区域照明电耗',
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          stack: '1777562657152888832',
        },
      ],
      unit: 'kWh' // 电耗单位改为kWh
    },
    {
      xaxisList: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00',
      ],
      yaxisList: [
        {
          name: '设备机房电耗',
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          stack: '1777562657152888832',
        },
      ],
      unit: 'kWh'
    },
    {
      xaxisList: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00',
      ],
      yaxisList: [
        {
          name: '辅助机房电耗',
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          stack: '1777562657152888832',
        },
      ],
      unit: 'kWh'
    },
    {
      xaxisList: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00',
      ],
      yaxisList: [
        {
          name: '太阳能发电量',
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          stack: '1777562657152888832',
        },
      ],
      unit: 'kWh'
    },
    {
      xaxisList: [
        '00:00', '01:00', '02:00', '03:00', '04:00', '05:00',
        '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
        '12:00', '13:00', '14:00',
      ],
      yaxisList: [
        {
          name: '柴油耗油量',
          data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          stack: '1777562657152888832',
        },
      ],
      unit: 'L'
    },
  ]

  // 过滤掉之前新增的数据
  typeList.value = typeList.value.filter(item => !item.dictCode.startsWith('new-'));

  // 先加载电耗数据
  const powerPromises = typeList.value.map((item, index) => {
    // 判断是否为电耗类型
    const isPowerType = item.itemName === ChartTypeEnum.CLEAN_POWER || 
                        item.itemName === ChartTypeEnum.SUPPORT_POWER;
    
    return getEleThisData({
      ...searchInfo,
      dictCode,
      itemName: item.itemName,
    })
      .then((res) => {
        // 电耗单位改为"kWh"，单耗保持"kWh/㎡"
        const unit = isPowerType ? 'kWh' : (res.unit || 'kWh/㎡');
        return {
          ...item,
          chartData: { ...res, unit },
          loading: false
        };
      })
      .catch((err) => {
        console.error(`获取${item.itemName}数据失败:`, err);
        // 使用模拟数据并设置正确单位
        return { 
          ...item, 
          chartData: { ...mockData[index], unit: isPowerType ? 'kWh' : mockData[index].unit },
          loading: false 
        };
      });
  });

  // 等待所有电耗数据加载完成
  const powerDataList = await Promise.all(powerPromises);

  // 再加载单耗数据
  const unitPromises = [ChartTypeEnum.CLEAN_POWER, ChartTypeEnum.SUPPORT_POWER].map(itemName => {
    return thisDataUnitConsumption({
      ...searchInfo,
      dictCode,
      itemName
    })
      .then(res => {
        let displayName = itemName;
        if (itemName === ChartTypeEnum.CLEAN_POWER) {
          displayName = ChartTypeEnum.CLEAN_UNIT;
        } else if (itemName === ChartTypeEnum.SUPPORT_POWER) {
          displayName = ChartTypeEnum.SUPPORT_UNIT;
        }
        return {
          dictCode: `new-${itemName}-${Date.now()}`,
          itemName: displayName,
          loading: false,
          chartData: { ...res, unit: res.unit || 'kwh/1000m2' }
        };
      })
      .catch(err => {
        console.error(`获取${itemName}单耗数据失败:`, err);
        return null;
      });
  });

  // 等待所有单耗数据加载完成
  const unitDataList = (await Promise.all(unitPromises)).filter(Boolean);

  // 合并所有数据并排序
  const allDataList = [...powerDataList, ...unitDataList];
  typeList.value = sortChartData(allDataList);
}

// 自定义排序函数，确保电耗在第一排，单耗在第二排
const sortChartData = (dataList) => {
  // 定义排序优先级（电耗在前，单耗在后）
  const powerOrder = [
    ChartTypeEnum.CLEAN_POWER,   // 洁净区电耗（第一排第一个）
    ChartTypeEnum.SUPPORT_POWER, // 支持区电耗（第一排第二个）
  ];
  
  const unitOrder = [
    ChartTypeEnum.CLEAN_UNIT,    // 洁净区单耗（第二排第一个）
    ChartTypeEnum.SUPPORT_UNIT,  // 支持区单耗（第二排第二个）
  ];
  
  // 其他图表类型
  const otherTypes = ['设备机房电耗', '辅助机房电耗', '太阳能发电量', '柴油耗油量'];

  // 合并完整排序顺序
  const order = [...powerOrder, ...unitOrder, ...otherTypes];

  return dataList.sort((a, b) => {
    const indexA = order.indexOf(a.itemName);
    const indexB = order.indexOf(b.itemName);

    // 按定义的优先级排序，未定义的排在后面
    return indexA === -1 ? (indexB === -1 ? 0 : 1) :
      indexB === -1 ? -1 : indexA - indexB;
  });
}
</script>

<style scoped lang="scss">
.content-box {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
  padding: 4px;
  overflow: auto;
  background: #fff;

  .chart-box {
    flex-shrink: 0;
    width: calc(100% / 2); // 每排显示2个图表
    min-height: 240px;
    padding: 4px;
    
    // 电耗图表（第一排）
    &:nth-child(1),
    &:nth-child(2) {
      order: 1;
      height: 50%; // 第一排占50%高度
    }
    
    // 单耗图表（第二排）
    &:nth-child(3),
    &:nth-child(4) {
      order: 2;
      height: 50%; // 第二排占50%高度
    }
    
    // 其他图表（第三排及以后）
    &:nth-child(n+5) {
      order: 3;
      height: auto; // 后续图表自动高度
    }
  }
} 
</style>